package adv.i31.robot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class Server implements Runnable {
	@Override
	public void run() {
		ServerSocket ss = null;
		Socket s = null;
		try {
			ss = new ServerSocket(123);

			synchronized (this) {
				// notify everyone that the server was set up successfully
				notifyAll();
			}

			System.out.println("awaiting connections");
			s = ss.accept();
			System.out.println("connection received");

			BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

			//System.out.println("Server received a message from " + s.getInetAddress() + ": " + br.readLine());

			JAXBContext context = JAXBContext.newInstance(Command.class);
			Unmarshaller u = context.createUnmarshaller();

			try {

				Command c = (Command) u.unmarshal(br);
				
				System.out.println("Server unmarshalled command: name=" + c.name);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (IOException | JAXBException e) {
			e.printStackTrace();
		} finally {
			try {
				s.close();
				ss.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}